<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*60);
ini_set('memory_limit', '128M');

$g_start = microtime(true);
require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
$dbconn = Connection::getInstance();

$toSubInfos = getToSubInfos($dbconn);
if(count($toSubInfos)>0){
	resultsGenerationSub($toSubInfos, $dbconn);
}

$toUnsubInfos = getToUnsubInfos($dbconn);
if(count($toUnsubInfos)>0){
	resultsGenerationUnsub($toUnsubInfos, $dbconn);
}

echo "\n". (microtime(true)-$g_start) . " seconds\n";



function getToSubInfos(Connection $db)
{
	$sql = " SELECT user_id, id FROM resultsgeneration_subscriber WHERE status='tosub' LIMIT 30";
	try{
		return $db->query($sql);
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getToUnsubInfos(Connection $db)
{
	$sql = " SELECT user_id, id FROM resultsgeneration_subscriber WHERE status='tounsub' LIMIT 20";
	try{
		return $db->query($sql);
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}	
}

function getUserInfo($userId, Connection $db)
{
	$sql = " SELECT u.*, s.domain AS siteurl FROM users u LEFT JOIN sites s ON u.site_id=s.id WHERE u.id=? ";
	try{
		$result = $db->query($sql, array($userId));
		if(count($result) > 0){
			return $result[0];
		}
		return false;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function resultsGenerationSub($toSubInfos, Connection $db)
{
	foreach($toSubInfos as $toSubInfo){
		$user = getUserInfo($toSubInfo['user_id'], $db);
		$params = array();
		$params['Command'] = 'ManageList';
		$params['ListCode'] = '98Bxu1D1C2MNx';
		$params['EmailAddress'] = trim($user['email']);
		$params['Type'] = 'Subscribe';
		$params['ReturnType'] = 'Code';
		$params['SignupIp'] = long2ip($user['ip']);
		$params['SignupDate'] = date('Y-m-d', $user['created']);
		$params['Source'] = $user['siteurl'];
		$params['SubID'] = $user['pub'];
		$params['Info[FirstName]'] = $user['firstname'];
		$params['Info[LastName]'] = $user['lastname'];
		$params['Info[Address]'] = $user['address1'];
		
		$ch = curl_init();
		$url = "https://api.resultsgeneration.com/api.php?&" . http_build_query($params, '', '&');
//echo $url. "\n";
		curl_setopt($ch, CURLOPT_URL, $url);
		//curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$content = curl_exec($ch);
		echo $user['id'] . " " . print_r($content);
		curl_close($ch);
		
		if(strtolower(trim($content)) == 'success'){
			setStatus($toSubInfo['id'], array('status' => 'sub', 'sub_date' => date('Y-m-d')), $db);
		}else{
			setStatus($toSubInfo['id'], array('status' => 'sub_failed', 'sub_date' => date('Y-m-d')), $db);
		}
	}
}

function resultsGenerationUnsub($toUnsubInfos, Connection $db)
{
	foreach($toUnsubInfos as $toUnsubInfo){
		$user = getUserInfo($toUnsubInfo['user_id'], $db);
		$params = array();
		$params['Command'] = 'ManageList';
		$params['ListCode'] = '98Bxu1D1C2MNx';
		$params['EmailAddress'] = trim($user['email']);
		$params['Type'] = 'Unsubscribe';
		$params['ReturnType'] = 'Code';
		
		$ch = curl_init();
		$url = "https://api.resultsgeneration.com/api.php?&" . http_build_query($params, '', '&');
//echo $url. "\n";
		curl_setopt($ch, CURLOPT_URL, $url);
		//curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$content = curl_exec($ch);
		echo $user['id'] . " " . print_r($content);
		curl_close($ch);
		
		setStatus($toUnsubInfo['id'], array('status' => 'unsub', 'unsub_date' => date('Y-m-d')), $db);
	}
}


function setStatus($toSubId, $set = array(), Connection $db)
{
	$query = array();
	$vars = array();
	foreach($set as $k => $v){
		$query[] = $k . '=?';
		$vars[] = $v;
	}
	$sql = " UPDATE resultsgeneration_subscriber SET " . implode(',', $query) . " WHERE id=? ";
	$vars[] = $toSubId;
	try{
		$result = $db->execute($sql, $vars);
		return $result;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

	
	
	
	
	
	
	